from channels.generic.websocket import AsyncWebsocketConsumer
from .groups import group, SendJson
import logging

log = logging.getLogger(__name__)


class Consumer(AsyncWebsocketConsumer):
    tag = 'chat'
    user = None

    async def connect(self):
        self.user = self.scope["user"]
        await self.accept()
        if not self.user or self.user.is_anonymous:
            await self.close()
            return

        # await self.channel_layer.group_add(self.tag, self.channel_name)
        await group.add(tag=self.tag, user=self.user, sp=self)

        # 关闭连接
        # await self.close()

    async def receive(self, text_data=None, bytes_data=None, **kwargs):

        is_json = await group.is_json(text_data=text_data)
        if not is_json:
            text = SendJson(flag=False, error_code=50000, error_msg='操作失败', **{'test': False}).to_dict()
            await self.send(text_data=text)
            return

        text = await group.decode_json(text_data=text_data)

        if text['type'] == 'all':
            await group.send_all_user("测试一下.")

        await self.send(text_data="Hello there!")

    async def disconnect(self, close_code):
        # await self.disconnect(close_code=400)
        # await self.channel_layer.group_discard(self.tag, self.channel_name)
        await group.delete(sp=self)


# Called when the socket closes
